import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

import { Dialog } from 'react-vant';

import Banner from '../Banner/index';
import Mode from '../Mode/index';
import Action from '../Action/index';

import { deviceId, ActionKey } from '@/utils/staticData';
import { getDeviceInfo } from '@/utils/model';
import useStore from '@/store/index';

import {
  btnFitersText, timeTempToMode
} from '@/utils/filters';

import './home.less';


export default function Home() {
  const Hejia = (window as any).Hejia;
  const location = useLocation();

  const { setInfo, info, startLoop, stopLoop } = useStore();

  useEffect(() => {
    setTimeout(() => {
      (window as any).bridge.callHandler(
        'setToolbarTitle',
        '小鸭智能空气炸锅XCX-888XY',
        null
      );
    }, 0);
  }, [location]);


  useEffect(() => {
    Hejia.ready(function () {
      getDeviceInfo();
      startLoop()
    });
  }, []);


  const handleModeChange = (val: number) => {
    console.log('handleModeChange:', val);
    const modeSettings = timeTempToMode(val);
    setInfo({
      ...info,
      ...{
        mode: val,
        temperature: modeSettings?.temperature,
        time: modeSettings?.time
      }
    });
  };

  const handleActionChange = (val: string, type: ActionKey) => {
    setInfo({ ...info, [type]: Number(val) });
  };


  type ControlParams = {
    deviceId?: string;
    parameters: {
      param: Array<{
        name: string;
        content: number;
      }>;
    };
  };


  const setDeviceControl = async (switchValue: number): Promise<void> => {
    const params: ControlParams = {
      // deviceId,
      parameters: {
        param: [{ name: 'switch', content: switchValue }]
      }
    };

    return new Promise((resolve, reject) => {
      Hejia.setControlParam(
        params,
        () => setTimeout(resolve, 2000),
        (msg: string, obj: any) => reject(new Error(`Device control failed: ${msg}`))
      );
    });
  };

  const handleRunningDevice = async () => {
    const result = await Dialog.confirm({
      message: '设备运行中，确定要取消运行吗',
      confirmButtonText: '确定',
      confirmButtonColor: 'var(--primary-color)',
    });

    if (result) {
      setInfo({ ...info, state: 0 });
      await setDeviceControl(0);
    }
  };

  const handleStoppedDevice = async () => {
    if (info.state === 2) {
      setInfo({ ...info, state:  0});
    } else {
      setInfo({ ...info, state:  1});
    }
    
    await setDeviceControl(1);
  };

  const onCooker = async () => {
    stopLoop();
    try {
      if (info.state === 1) {
        await handleRunningDevice();
      } else {
        await handleStoppedDevice();
      }
    } catch (error) {
      console.error('Operation failed:', error);
    } finally {
      startLoop();
    }
  };

  return (
    <div className="home">
      <div>
        <Banner />

        <Mode onModeChange={handleModeChange} />

        {/* 烹饪温度，烹饪时间 */}
        <Action onActionChange={handleActionChange} />

        <div className="home-mask-wapper">
          {(!info.isOnline || !!info.fault) && <div className="mask"></div>}
          <div className="footer">
            <div className="stop-btn" onClick={onCooker}>
              {btnFitersText(
                info.state,
                info.prompt
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
